package com.sh.web.controller;

import com.sh.bean.Resuser;
import com.sh.service.ResuserBiz;
import com.sh.utils.JwtTokenUtil;
import com.sh.web.model.ResponseResult;
import com.sh.web.model.ResuserVo;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@RestController
@Slf4j
@RequestMapping("/ressecurity")
public class UserController {

    @Autowired
    private ResuserBiz resuserBiz;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtTokenUtil jwtUtil;
    @Value("${res.sign.time}")
    private String sign;


    @PostMapping("/register")
    public ResponseResult register(@RequestBody @Valid ResuserVo resuserVo) {
        try {
            int userid = this.resuserBiz.regUser(resuserVo);
            resuserVo.setUserid(userid);
            resuserVo.setPassword("");
            return ResponseResult.ok("注册成功").setData(resuserVo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("注册失败");
        }
    }

    @PostMapping("/login")
    public ResponseResult login(@RequestBody ResuserVo resuserVo, HttpSession session) {
        System.out.println("现在的状态： " + sign + "   !!!!!");
        String captcha = (String) session.getAttribute("captcha");

//        if(captcha == null || !captcha.equalsIgnoreCase(resuserVo.getCaptcha())){
//            return ResponseResult.error("验证码错误");
//        }
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(resuserVo.getUsername(),
                        resuserVo.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        HashMap<String, String> playload = new HashMap<>();
        playload.put("username", userDetails.getUsername());
        playload.put("userid", String.valueOf(((Resuser) userDetails).getUserid()));
        playload.put("roles", "user");
        playload.put("email", ((Resuser) userDetails).getEmail());
        String token = jwtUtil.encodeJwt(playload);
        return ResponseResult.ok("登录成功").setData(token);
    }

    @PostMapping("/loginByTel")
    public ResponseResult loginByTel( HttpSession session) {
        String telValcode = (String) session.getAttribute("telValcode");
        ResuserVo resuserVo = new ResuserVo();
        resuserVo.setUsername(telValcode);
        resuserVo.setPassword(telValcode);
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken("ccc","a"  )  );
        SecurityContextHolder.getContext().setAuthentication(authentication);
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        HashMap<String, String> playload = new HashMap<>();
        playload.put("username", userDetails.getUsername());
        playload.put("userid", String.valueOf(((Resuser) userDetails).getUserid()));
        playload.put("roles", "user");
        playload.put("email", ((Resuser) userDetails).getEmail());
        String token = jwtUtil.encodeJwt(playload);
        return ResponseResult.ok("登录成功").setData(token);

    }

    @PostMapping("/logout")
    public ResponseResult logout(@RequestHeader("token") String token) {
        System.out.println("token:" + token);
        return ResponseResult.ok("注销成功");
    }

    @PostMapping("/check")
    public ResponseResult check() {
        log.info("没有问题，请求可以过来");
        Resuser resuser = (Resuser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        log.info("用户信息：{}", resuser);
        resuser.setPassword("");
        return ResponseResult.ok("验证成功").setData(resuser);
    }

}
